package test1;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.context.support.GenericApplicationContext;
import test1.entity.Account;
import test1.mapper.AccountMapper;
import test1.service.AccountService;
import test1.service.AccountService2;
import test1.service.AccountService3;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author: mornd
 * @dateTime: 2023/5/15 - 20:16
 */

@Slf4j
public class App {
    public static void main(String[] args) throws Throwable {
        GenericApplicationContext context = new GenericApplicationContext();

        AnnotationConfigUtils.registerAnnotationConfigProcessors(context.getDefaultListableBeanFactory());
        ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());

        context.registerBean(Config.class);
        context.refresh();

//        AccountService bean = context.getBean(AccountService.class);
//        AccountService2 bean = context.getBean(AccountService2.class);
        AccountService3 bean = context.getBean(AccountService3.class);

        CountDownLatch latch = new CountDownLatch(2);

        MyThread t1 = new MyThread(() -> {
//            synchronized (App.class) {
                bean.transfer(1, 2, 1000);
//            }
            latch.countDown();
            System.out.println("**************************");
        }, "t1", "red");
        t1.start();

        MyThread t2 = new MyThread(() -> {
//            synchronized (App.class) {
                bean.transfer(1, 2, 1000);
//            }
            latch.countDown();
            System.out.println("**************************");
        }, "t2", "blue");
        t2.start();

        log.debug("main线程执行完毕");
        latch.await();
        AccountMapper accountMapper = context.getBean(AccountMapper.class);

        log.debug("最终账户余额为：" + accountMapper.getById(1) + "," + accountMapper.getById(2));
    }


    static class MyThread extends Thread {
        private String color;

        public MyThread(Runnable target, String name, String color) {
            super(target, name);
            this.color = color;
        }

        @Override
        public void run() {
            MDC.put("thread", color);
            super.run();
            MDC.remove("thread");
        }
    }
}
